package com.meida.generator;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;
import com.baomidou.mybatisplus.generator.config.po.TableFill;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.meida.common.utils.FlymeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 代码生成器
 */
@Component
public class GeneratorCode {

    @Autowired
    public DataSourceProperties dataSourceProperties;

    public void init(GenerateConfig generateConfig) {

        AutoGenerator mpg = new AutoGenerator();

        String tableName = generateConfig.getTableName();

        if (FlymeUtils.isEmpty(tableName)) {
            System.err.println("错误:请设置要生成的数据表名称");
            return;
        }
        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        gc.setOutputDir(generateConfig.getOutputDirectory());
        //gc.setOutputDir(baseOutPath + "/src/main/java");
        gc.setFileOverride(generateConfig.getOverride());
        //ActiveRecord特性
        gc.setActiveRecord(false);
        // XML ResultMap
        gc.setBaseResultMap(false);
        // XML columList
        gc.setBaseColumnList(false);
        gc.setEnableCache(false);
        gc.setSwagger2(true);
        // 自动打开输出目录
        gc.setOpen(false);
        gc.setAuthor(generateConfig.getAuthor());
        //主键策略
        gc.setIdType(IdType.ID_WORKER);

        // 自定义文件命名，注意 %s 会自动填充表实体属性！
        if (generateConfig.getGeneratorInterface()) {
            gc.setServiceName("%sService");
            gc.setServiceImplName("%sServiceImpl");
        } else {
            gc.setServiceName("%sService");
            gc.setServiceImplName("%sService");
        }
        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setDbType(DbType.MYSQL);
        dsc.setDriverName(dataSourceProperties.getDriverClassName());
        dsc.setUsername(dataSourceProperties.getUsername());
        dsc.setPassword(dataSourceProperties.getPassword());
        dsc.setUrl(dataSourceProperties.getUrl());
        dsc.setTypeConvert(new MySqlTypeConvert() {
            // 自定义数据库表字段类型转换【可选】
            @Override
            public DbColumnType processTypeConvert(GlobalConfig globalConfig, String fieldType) {
                //tinyint转换成Boolean
                if (fieldType.toLowerCase().contains("tinyint")) {
                    return DbColumnType.BOOLEAN;
                }
                //将数据库中datetime转换成date
                if (fieldType.toLowerCase().contains("datetime")) {
                    return DbColumnType.DATE;
                }
                return (DbColumnType) super.processTypeConvert(globalConfig, fieldType);
            }
        });

        mpg.setDataSource(dsc);


        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setCapitalMode(false);
        strategy.setEntityLombokModel(true);
        strategy.setEntityTableFieldAnnotationEnable(false);
        strategy.setControllerMappingHyphenStyle(true);
        // 此处可以移除表前缀表前缀
        strategy.setTablePrefix(generateConfig.getRemoveTablePrefix());


        // 表名生成策略
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setRestControllerStyle(true);
        // 字段生成策略
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setSuperEntityColumns("createTime", "updateTime", "createUser", "updateUser");
        // mapper 父类
        strategy.setSuperMapperClass("com.meida.common.mybatis.base.mapper.SuperMapper");
        // 实体父类
        strategy.setSuperEntityClass("com.meida.common.mybatis.base.entity.AbstractEntity");
        // 接口父类
        strategy.setSuperServiceClass("com.meida.common.mybatis.base.service.IBaseService");
        // 接口实现类父类
        strategy.setSuperServiceImplClass("com.meida.common.mybatis.base.service.impl.BaseServiceImpl");

        strategy.setSuperControllerClass("com.meida.common.springmvc.base.BaseController");

        // 需要生成的表
        // strategy.setInclude(generateConfig.getIncludeTables());
        // 需要生成的表
        strategy.setInclude(tableName);
        // 公共字段填充
        ArrayList<TableFill> tableFills = new ArrayList<>();
        tableFills.add(new TableFill("createTime", FieldFill.INSERT));
        tableFills.add(new TableFill("updateTime", FieldFill.UPDATE));
        tableFills.add(new TableFill("createUser", FieldFill.INSERT));
        tableFills.add(new TableFill("updateUser", FieldFill.UPDATE));
        strategy.setTableFillList(tableFills);


        mpg.setStrategy(strategy);


        // 包配置
        PackageConfig pc = new PackageConfig();
        //父包名
        pc.setParent(generateConfig.getParentPackage());
        //父包模块名
        //pc.setModuleName(generateConfig.getModuleName());
        //实体类父包
        pc.setModuleName(generateConfig.getModuleName().substring(generateConfig.getModuleName().lastIndexOf("-") + 1));
        pc.setEntity("client.entity");
        //controller父包
        pc.setController("provider.controller");
        //mapper父包
        pc.setMapper("provider.mapper");
        //xml父包
        pc.setXml("provider.mapper.xml");
        //service父包
        if (generateConfig.getGeneratorInterface()) {
            pc.setServiceImpl("provider.service.impl");
            pc.setService("provider.service");
        } else {
            pc.setServiceImpl("provider.service");
            pc.setService("provider.service");
        }

        // 自定义配置
        // 注入自定义配置，可以在 模板 中使用 cfg.abc 【可无】
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                Map map = new HashMap<String, Object>(1);
                String alias = FlymeUtils.getAlias(tableName);
                map.put("alias", alias);
                map.put("apiPackName", pc.getParent() + ".client.api");
                this.setMap(map);
            }
        };
        String jsPath = "/templates/api.js.vm";
        String vuePath = "/templates/index.vue.vm";
        List<FileOutConfig> focList = new ArrayList<>();
        // 自定义配置会被优先输出
        focList.add(new FileOutConfig(jsPath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return gc.getOutputDir() + "/js/" + pc.getModuleName()
                        + "/" + tableInfo.getName().replaceFirst(pc.getModuleName() + "_", "").replace("_", "-") + ".js";
            }
        });
        focList.add(new FileOutConfig(vuePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return gc.getOutputDir() + "/view/" + pc.getModuleName()
                        + "/" + tableInfo.getName().replaceFirst(pc.getModuleName() + "_", "").replace("_", "-") + "/index.vue";
            }
        });

        String baseOutPath = generateConfig.getBaseOutPath();
        if (FlymeUtils.isEmpty(baseOutPath)) {
            String path = System.getProperty("user.dir");
            if (generateConfig.getBaseProject()) {
                baseOutPath = path.substring(0, path.lastIndexOf("\\") - 10);
            } else {
                baseOutPath = path.substring(0, path.lastIndexOf("\\"));
            }
        }

        String finalBaseOutPath = baseOutPath;
        // 调整 xml 生成目录
        focList.add(new FileOutConfig("/templates/mapper.xml.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return finalBaseOutPath + getBasePath(generateConfig) + "-provider/" + getPackName(pc, pc.getXml()) + tableInfo.getXmlName() + ".xml";
            }
        });

        // 调整 service 生成目录
        focList.add(new FileOutConfig("/templates/service.java.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return finalBaseOutPath + getBasePath(generateConfig) + "-provider/" + getPackName(pc, pc.getService()) + tableInfo.getServiceName() + ".java";
            }
        });

        // 调整 serviceImpl 生成目录
        focList.add(new FileOutConfig("/templates/serviceImpl.java.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return finalBaseOutPath + getBasePath(generateConfig) + "-provider/" + getPackName(pc, pc.getServiceImpl()) + tableInfo.getServiceImplName() + ".java";
            }
        });

        // 调整 mapper 生成目录
        focList.add(new FileOutConfig("/templates/mapper.java.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return finalBaseOutPath + getBasePath(generateConfig) + "-provider/" + getPackName(pc, pc.getMapper()) + tableInfo.getMapperName() + ".java";
            }
        });

        // 调整 controller 生成目录
        focList.add(new FileOutConfig("/templates/controller.java.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return finalBaseOutPath + getBasePath(generateConfig) + "-provider/" + getPackName(pc, pc.getController()) + tableInfo.getControllerName() + ".java";
            }
        });
        // 调整 entity 生成目录
        focList.add(new FileOutConfig("/templates/entity.java.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {

                return finalBaseOutPath + getBasePath(generateConfig) + "-client/" + getPackName(pc, pc.getEntity()) + tableInfo.getEntityName() + ".java";
            }
        });


        // 调整 entity 生成目录演示
        focList.add(new FileOutConfig("/templates/interface.java.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return finalBaseOutPath + getBasePath(generateConfig) + "-client/" + getPackName(pc, "client.api") + tableInfo.getEntityName() + "RemoteApi.java";
            }
        });


        // 自定义模板配置
        // 放置自己项目的 src/main/resources/templates 目录下, 默认名称可以不配置，也可以自定义模板名称
        TemplateConfig tc = new TemplateConfig();
        tc.setService(null);
        tc.setServiceImpl(null);
        tc.setMapper(null);
        tc.setController(null);
        tc.setEntity(null);
        tc.setXml(null);
        //如上任何一个模块如果设置 空 OR Null 将不生成该模块。
        mpg.setTemplate(tc);
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);
        mpg.setPackageInfo(pc);
        // 执行生成
        mpg.execute();
    }

    public static String getPackName(PackageConfig pc, String name) {
        String clientBasePath = pc.getParent() + "." + name;
        return "src/main/java/" + clientBasePath.replace(".", "/") + "/";
    }

    public static String getBasePath(GenerateConfig config) {
        String path = "";
        if (FlymeUtils.isEmpty(config.getModuleName())) {
            path = "/" + config.getBaseModule() + "/" + config.getBaseModule();
        } else {
            path = "/" + config.getBaseModule() + "/" + config.getModuleName() + "/" + config.getModuleName();
        }
        return path;
    }


}